<template>
  <div v-if="visible" class="">
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :modal-class="modalClass"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <a-spin :loading="loading" dot style="width: 100%;">
        <a-form ref="formRef" :model="formModel">
          <div ref="searchRef">
            <a-space>
              <a-upload
                :custom-request="customUpload"
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                :show-file-list="false"
              >
                <template #upload-button>
                  <a-button type="primary">
                    <template #icon><icon-upload /></template>导入文件
                  </a-button>
                </template>
              </a-upload>
              <a-button type="text" @click="downloadImportDemo('test-demo.xls')">下载导入模板</a-button>
            </a-space>
            <a-typography-paragraph style="margin-top: 20px;">
              <ul>
                <li>支持导入格式为xlsx的文件(手动修改文件后缀无效)</li>
                <li>模版中的表头不可更改，不可删除</li>
                <li>数据记录不要超过1000条</li>
              </ul>
            </a-typography-paragraph>
          </div>
          <div ref="tableContainerRef">
            <a-table
              ref="tableRef"
              row-key="id"
              :pagination="false"
              :data="formModel.items"
              :bordered="{ wrapper: true, cell: true }"
              :scroll="tableScroll"
              column-resizable
            >
              <template #columns>
                <a-table-column title="名称" data-index="name" :width="160">
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="`items.${rowIndex}.name`" label="" required :hide-label="true">
                      <a-input v-model="record.name" max-length="60" placeholder=""/>
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="详情" data-index="info" :width="240">
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="`items.${rowIndex}.info`" label="" required :hide-label="true">
                      <a-textarea v-model="record.info" placeholder=""/>
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="时间" data-index="created_at" :width="160">
                  <template #cell="{ record, rowIndex }">
                    <a-form-item :field="`items.${rowIndex}.created_at`" label="" :hide-label="true">
                      <a-date-picker v-model="record.created_at" show-time format="YYYY-MM-DD HH:mm:ss"/>
                    </a-form-item>
                  </template>
                </a-table-column>
                <a-table-column title="操作" data-index="operations" align="center" fixed="right" :width="85">
                  <template #cell="{ record }">
                    <a-button type="text" status="danger" size="mini" @click="del(record)">删除</a-button>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </div>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref, watch, reactive, computed, onMounted, onUnmounted } from 'vue';
  import { Message } from '@arco-design/web-vue';

  import { useAdminStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import useVisible from '@/hooks/visible';
  import { downloadFile } from '@/utils';
  import tool from '@/utils/tool';
  import { apiSaveList, apiImport } from '@/api/test';
  import { downloadPath } from '@/api/common';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
  });
  const emit = defineEmits(['selectCallback']);

  const adminStore = useAdminStore();
  const { loading, setLoading } = useLoading(true);
  const baseFormModel = () => {
    return {
      id: '',
      items: [],
    };
  };
  const formRef = ref();
  const formModel = ref(baseFormModel());
  const tableScroll = ref({
    x: '100%',
    y: '100%',
  });
  const modalStyle = {
    width: '85%',
    height: '90%',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };
  const modalClass = `modal-${tool.generateId()}`;

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const tableRef = ref();

  const { visible, setVisible } = useVisible(false);
  const dialogTitle = ref();

  const settingFixedPage = () => {
    const workHeight = document.querySelector(`.${modalClass}`).offsetHeight - 168;
    const tableHeight = workHeight - searchRef.value.offsetHeight;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    settingFixedPage();
  };

  // 列表
  const fetchData = async () => {
    setLoading(true);
    try {

    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 表单重置
  const reset = async () => {
    //
  };

  // 提交
  const submit = async (done) => {
    try {
      const ruleRes = await formRef.value?.validate();
      if (!ruleRes) {
        if (formModel.value.items.length <= 0) {
          Message.info('请导入数据');
          done(false);
        } else {
          await apiSaveList(formModel.value);
          done();
          emit('saveCallback');
        }
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };

  const del = (row) => {
    const index = formModel.value.items.indexOf(row);
    if (index !== -1) {
      formModel.value.items.splice(index, 1);
    }
  };
  // 导入
  const customUpload = (option) => {
    const { onProgress, onError, onSuccess, fileItem, name = 'file' } = option;
    const controller = new AbortController();

    (async function requestWrap() {
      const formData = new FormData();
      formData.append(name, fileItem.file);
      onProgress(20);

      try {
        setLoading(true);
        const res = await apiImport(formData);
        onProgress(100);
        onSuccess(res);
        const { data } = res;
        data.forEach((item) => {
          formModel.value.items.push({
            name: item.name,
            info: item.info,
            created_at: item.created_at,
          });
        });
        setLoading(false);
      } catch (error) {
        onError(error);
        setLoading(false);
      }
    })();
    return {
      abort() {
        controller.abort();
      },
    };
  };
  // 下载导入模板
  const downloadImportDemo = (path) => {
    downloadFile(`${downloadPath()}${path}`);
  };

  const dialogCancel = () => {
    setVisible(false);
  };
  const dialogBeforeOk = (done) => {
    submit(done);
  };

  // 初始化
  const initData = async () => {
    setVisible(true);
    dialogTitle.value = '导入';

    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    settingFixedPage();
  };

  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
  // 暴露方法【给父级调用】
  defineExpose({
    initData,
  });
</script>

<style scoped lang="less">
  .arco-table-container .arco-form-item {
    margin-bottom: 0;
  }
</style>
